package com.xyc.petmallsystem.controller;

import com.xyc.petmallsystem.pojo.Personal;
import com.xyc.petmallsystem.pojo.User;
import com.xyc.petmallsystem.repository.CarsRepository;
import com.xyc.petmallsystem.repository.PersonalRepository;
import com.xyc.petmallsystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Joel
 * @date 2021/11/17
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserRepository userRepository;

    @Autowired
    PersonalRepository personalRepository;

    @Autowired
    CarsRepository carsRepository;

    /*格式化返回当前时间*/
    private Date dateFormat() throws ParseException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.parse(sdf.format(date));
    }

    /*
    查询所有
     */
    @RequestMapping("/find")
    public List<User> findAll() {
        return userRepository.findAll();
    }

    /*
    分页
     */
    @GetMapping("/findPage/{page}/{size}")
    public Page<User> findPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageRequest pageable = PageRequest.of(page - 1, size);
        return userRepository.findAll(pageable);
    }

    /*
    插入一条数据
     */
    @PostMapping("/save")
    public String save(@RequestBody User user) throws ParseException {
        System.out.println("修改前的user：" + user);


        //判断 name是否存在
        User judgeUser = userRepository.findByName(user.getName());
        if (judgeUser != null) {
            return "can not repeat"; // 若用户名已存在 ，则不能注册
        }

        Date now = dateFormat();
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setName(user.getName());
        newUser.setPwd(user.getPwd());
        newUser.setMyTime(now);
        User result = userRepository.save(newUser);
        System.out.println("修改后的user:" + result);
        if (result != null) {  // 成功插入一条用户记录
            /*
            生成个人中心
             */
            Personal personal = new Personal();
            personal.setUser_id(newUser.getId());
            personal.setPost(100000);
            personal.setNickname(newUser.getName());
            personal.setSex(1);
            personal.setReceive(newUser.getName());
            personal.setPhone("15800001111");
            personal.setAddress("北京市朝阳区向阳街150号\n");
            System.out.println("注册个人中心:" + personal);
            personalRepository.save(personal);
            return "success";
        }

        return "error";
    }

    /*
    查询指定id
     */
    @GetMapping("/findById/{id}")
    public User findById(@PathVariable("id") Integer id) {
        System.out.println("要查询的id：" + id); // 输入要查询的id
        return userRepository.findById(id).get();
    }

    /*
    update  更新
     */
    @PutMapping("/update")
    public String update(@RequestBody User user) throws ParseException { // 小陈 222
        System.out.println("更新的user：" + user);
        Date now = dateFormat();
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setName(user.getName());
        newUser.setPwd(user.getPwd());
        newUser.setMyTime(now);

        User result = userRepository.save(newUser); // 根据id更新  保存最新修改时间

        if (result != null) {
            return "success";
        } else {
            return "error";
        }

    }

    /*
    根据id 删除
     */
    @DeleteMapping("/delById/{id}")
    public void delById(@PathVariable("id") Integer id) {
        System.out.println("删除id:" + id);
        userRepository.deleteById(id);
        userRepository.setAutoIncrement(id); // 只针对最后一条
    }


    /*
    登录判断 用户名和密码
     */
    @PostMapping("/login")
    public String login(@RequestBody User user) {
        System.out.println("登录要判断的用户:" + user);

        User result = userRepository.login(user.getName(), user.getPwd());
        if (result != null) {
            if (result.getName().equals(user.getName()) && result.getPwd().equals(user.getPwd())) {
                return "success";
            } else {
                return "error";
            }
        }
        return "error";
    }


    /*
    根据name来获取id
    */
    @GetMapping("/getIdByName/{name}")
    public Integer getIdByName(@PathVariable String name) {
        Integer id = userRepository.getUserIdByName(name);
        if (id != null)
            return id;
        return -1;
    }

    /*
    修改密码
     */
    @GetMapping("/change/{name}/{pwd0}/{pwd1}/{pwd2}")
    public String change(@PathVariable String name,
                         @PathVariable String pwd0,
                         @PathVariable String pwd1,
                         @PathVariable String pwd2) {
        User user = userRepository.findByName(name);
        //判断原密码正确性
        String password = user.getPwd();
        if (!pwd0.equals(password)) {
            System.out.println("原密码错误");
            return "Original password error";
        }
        if (!pwd1.equals(pwd2)) {
            System.out.println("密码不一致");
            return "Inconsistent passwords";
        }
        //符合条件，修改密码
        user.setPwd(pwd1);
        userRepository.save(user);
        System.out.println("修改成功，新密码为:" + user.getPwd());
        return "success";
    }

    /*
    注销账号
     */
    @GetMapping("/layout/{loginName}")
    public void layout(@PathVariable String loginName) {
        // 根据用户名找到 user_id
        User user = userRepository.findByName(loginName);
        System.out.println("注销的用户:" + loginName + ",编号:" + user.getId());
        Integer user_id = user.getId();
        // 先删除购物车
        carsRepository.delByUserId(user_id);
        // 删除个人中心
        personalRepository.delByUserId(user_id);
        // 删除用户表
        userRepository.deleteById(user_id);
    }

}
